"use strict";

import Vue from "vue";
import _axios from "axios";
import router from "@/router";
import store from "@/store";
import * as types from "@/store/modules/general/mutation_types";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  baseURL: process.env.baseURL || process.env.apiUrl || "",
  timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const axios = _axios.create(config);

axios.interceptors.request.use(
  (config) => {
    if(config.hideLoading){
      // 不加载loading的overlay
    }else{
      store.commit("general/" + types.LOADING_START)
    }   

    let token = store.getters["auth/token"] || null;
    let authorized = token && token.checkValid();

    if (authorized) {
      config.headers.common["Authorization"] = "Bearer " + token.access_token;
    }

    return config;
  },
  (error) => {
    store.commit("general/" + types.LOADING_STOP);
    // Vue.$dialog.error({
    //   title: "请求错误:" + error.response.status,
    //   text: "error.response.data",
    // });
    alert(error);
    return Promise.reject(error);
  }
);

// Add a response interceptor
axios.interceptors.response.use(
  (data) => {
    store.commit("general/" + types.LOADING_STOP);

    return data;
  },
  (error) => {
    store.commit("general/" + types.LOADING_STOP);
    if(!error.response){
      // 如果不存在error.response，比如可能从cancel token来
      return Promise.reject(error);
    }
    if (error.response.config.url.endsWith("auth/login")) {
      //因为登陆的错误处理已经在调用中弄处理，就不走下面的弹窗错误提醒逻辑
      return Promise.reject(error);
    } else if (
      error.response.config.url.endsWith("api/role") &&
      error.response.status == 404
    ) {
      //查找角色报404错误的
      return Promise.reject(error);
    } else if (error.response && error.response.status >= 400) {
      let error_data = error.response.data;
      if (
        error.request.responseType === "arraybuffer" &&
        error.response.data instanceof ArrayBuffer
      ) {
        error_data = JSON.parse(Buffer.from(error_data).toString("utf8"));
      }
      let msg = error_data.msg || error_data.message || error_data.error;
      if (error_data.errors) {
        // schema error msg
        msg = JSON.stringify(error_data.errors);
      }
      else if (
        msg &&
        (msg === "Bad credentials" || msg === "Signature verification failed")
      ) {
        router.push({ name: "SignIn" });
      } else {
        Vue.prototype.$dialog.error({
          title: "错误码：" + error.response.status,
          text: "错误信息：" + msg,
        });
      }
      return Promise.reject(error);
    } else {
      // error anyway
      return Promise.reject(error);
    }
  }
);

const Plugin = {};

Plugin.install = function (Vue) {
  Vue.axios = axios;
  window.axios = axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return axios;
      },
    },
    $axios: {
      get() {
        return axios;
      },
    },
  });
};

Vue.use(Plugin);


export default Plugin;
export { axios, Plugin };
